<?php

namespace App\Console\Commands;

use App\Repository\Models\Menu;
use App\Repository\Models\Action;
use Illuminate\Console\Command;
use Illuminate\Routing\Router;
use Illuminate\Support\Arr;
use Illuminate\Routing\Route;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;


//自动根据路由生成操作命令
class ActionGenerateCommand extends Command 
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'action:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '自动根据路由生成操作命令';


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $router = app('router');
        $routes = $router->getRoutes();
        $data = [];
        foreach ($routes as $route) {
            $name = array_get($route,'action.as');
            if(Str::startsWith($name,'backend')){
                $find = Action::where('action',$name)->first();
                if($find)  continue;
                $group = array_get(explode('.',$name),'1','other');
                $data[] = [
                    'group' => $group,
                    'name' => $name,
                    'action' => $name,
                    'description' => $name,
                    'state' => 1,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ];
            }
        }
        if(count($data)){
            Action::insert($data);
        }
        $this->line('操作自动生成成功!');
    }

}
